package js.dwim.web;

import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.MessageType;
import com.google.appengine.api.xmpp.SendResponse;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import js.dwim.domain.CommSession;
import js.dwim.server.CommandInterpreter;
import js.dwim.server.Persistence;

public class XmppCommServlet
        extends HttpServlet
{
    private static final long        serialVersionUID = 1L;
    private static final XMPPService xmppService      = XMPPServiceFactory.getXMPPService();

    public static SendResponse sendMessage( CommSession session, String msg )
    {
        Message message = new MessageBuilder()
                .withRecipientJids( session.getJid() )
                .withMessageType( MessageType.CHAT ).withBody( msg ).build();

        return xmppService.sendMessage( message );
    }

    public void doPost( HttpServletRequest request, HttpServletResponse response )
            throws IOException
    {
        Message message     = xmppService.parseMessage( request );
        CommSession session = Persistence.getSession( message );

        CommandInterpreter.process( session, message.getBody() );

        Persistence.updateSession( session );
    }
}
